package com.caishi.lkx.user.service.impl;

import com.caishi.lkx.common.config.DiamondConfig;
import com.caishi.lkx.user.ienum.status.UserGroupStatus;
import com.caishi.lkx.user.model.re.UserGroupReModel;
import com.caishi.lkx.user.service.IGroupService;
import com.caishi.lkx.user.service.IMemberService;
import com.caishi.lkx.user.service.IUserGroupReService;
import com.zzw.common.Wrappers;
import com.zzw.common.entity.IBSMapper;
import com.zzw.common.lock.RedissonLock;

import com.caishi.lkx.user.mapper.re.UserGroupReMapper;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeoutException;

@Service
public class UserGroupReServiceImpl implements IUserGroupReService {
    @Resource
    private UserGroupReMapper userGroupReMapper;
    @Resource
    private DiamondConfig diamondConfig;
    @Resource
    private IGroupService groupService;
    @Resource
    private IMemberService memberService;

    @Override
    public IBSMapper<UserGroupReModel, Long> getMapper() {
        return userGroupReMapper;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean bind(Long groupId, String currentUserId, String currentIp, BigDecimal longitude, BigDecimal latitude) throws InterruptedException, TimeoutException {
        RedissonLock.lock("user:bind:group:" + currentUserId, k -> {
            List<UserGroupStatus> statuseList = new ArrayList<>();
            statuseList.add(UserGroupStatus.review);
            statuseList.add(UserGroupStatus.pass);
            //过期时间 初始设置绑定后3个月
            LocalDate expireDate = LocalDate.now().plusDays(diamondConfig.getUserGroupInitExpireDay());
            //1.查看是否有审核中或者审核通过的记录
            UserGroupReModel userGroupReModel = this.selectOne(Wrappers.<UserGroupReModel>lambdaQuery().eq(UserGroupReModel::getUserId, currentUserId).in(UserGroupReModel::getStatus, statuseList));
            if (null == userGroupReModel) {
                userGroupReModel = UserGroupReModel.builder().groupId(groupId).userId(currentUserId).build();
            }
            userGroupReModel.setExpireTime(expireDate);
            userGroupReModel.setStatus(UserGroupStatus.review);
            if (this.checkUserBindGroup(groupId, currentIp, longitude, latitude)) {
                userGroupReModel.setStatus(UserGroupStatus.pass);
                memberService.bindGroup(currentUserId,groupId);
            }
            if (null != userGroupReModel.getId()) {
                this.simpleUpdate(userGroupReModel);
            } else {
                this.insert(userGroupReModel);
            }

        });
        return true;
    }

    public boolean checkUserBindGroup(Long groupId, String currentIp, BigDecimal longitude, BigDecimal latitude) {
        //GroupModel groupModel = groupService.currentGroup(currentIp, longitude, latitude, null);
       // return null != groupModel && groupId.equals(groupModel.getId());
        return false;
    }

    @Override
    public Boolean unBind(String currentUserId) throws InterruptedException, TimeoutException {
        RedissonLock.lock("user:bind:group:" + currentUserId, k -> {
            List<UserGroupStatus> statuseList = new ArrayList<>();
            statuseList.add(UserGroupStatus.review);
            statuseList.add(UserGroupStatus.pass);
            //1.查看是否有审核中或者审核通过的记录
            UserGroupReModel userGroupReModel = new UserGroupReModel();
            userGroupReModel.setStatus(UserGroupStatus.unBind);

            this.update(userGroupReModel,Wrappers.<UserGroupReModel>lambdaUpdate().eq(UserGroupReModel::getUserId, currentUserId).in(UserGroupReModel::getStatus, statuseList));


        });
        return true;
    }

    @Override
    public UserGroupReModel currentUserGroup(String userId) {
        List<UserGroupStatus> statusList = new ArrayList<>();
        statusList.add(UserGroupStatus.review);
        statusList.add(UserGroupStatus.pass);
       return this.selectOne(Wrappers.<UserGroupReModel>lambdaQuery().eq(UserGroupReModel::getUserId, userId).in(UserGroupReModel::getStatus, statusList));
    }

    @Override
    public Boolean changeStatus(List<Long> ids, UserGroupStatus status) {
        this.update(null,Wrappers.<UserGroupReModel>lambdaUpdate().set(UserGroupReModel::getStatus,status).in(UserGroupReModel::getId,ids));
        if(UserGroupStatus.pass.equals(status)){
            this.selectBatchIds(ids).parallelStream().forEach(re -> memberService.bindGroup(re.getUserId(),re.getGroupId()));
        }
        return true;
    }

    @Override
    public Boolean updateExpireDate(String currentUserId, LocalDate newDate, Integer days) {
        if(null == newDate && null == days){
            return false;
        }
        if(null == newDate){
            newDate = LocalDate.now().plusDays(days);
        }
        this.update(null,Wrappers.<UserGroupReModel>lambdaUpdate().set(UserGroupReModel::getExpireTime,newDate)
                .eq(UserGroupReModel::getId,currentUserId)
                .eq(UserGroupReModel::getStatus,UserGroupStatus.pass));
        return true;
    }
}
